package com.flow.framework.web.holder;

import com.flow.framework.base.properties.component.RequestConfigProperties;
import com.flow.framework.base.properties.component.ResponseConfigProperties;
import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.web.context.RequestResponseContext;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求和响应的上下文信息持有者，上下文信息主要是用来辅助记录入访日志的
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/12/25
 */
@Slf4j
public class RequestResponseContextHolder {
    private static final ThreadLocal<RequestResponseContext> REQUEST_RESPONSE_CONTEXT_THREAD_LOCAL = new ThreadLocal<>();

    public static RequestResponseContext initContext(long startTime,
                                                     HttpServletRequest httpServletRequest,
                                                     HttpServletResponse originalResponse,
                                                     RequestConfigProperties requestConfigProperties,
                                                     ResponseConfigProperties responseConfigProperties) {
        RequestResponseContext requestResponseContext = new RequestResponseContext(startTime, httpServletRequest,
                originalResponse, requestConfigProperties, responseConfigProperties);
        REQUEST_RESPONSE_CONTEXT_THREAD_LOCAL.set(requestResponseContext);
        return requestResponseContext;
    }

    public static RequestResponseContext getContext() {
        RequestResponseContext requestResponseContext = REQUEST_RESPONSE_CONTEXT_THREAD_LOCAL.get();
        if (null == requestResponseContext) {
            log.error("request response context is null.");
            throw new CheckedException(SystemErrorCode.API_SERVER_ERROR);
        }
        return requestResponseContext;
    }

    public static void clear() {
        REQUEST_RESPONSE_CONTEXT_THREAD_LOCAL.remove();
    }
}